package com.example.demo.aop;

import com.example.demo.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Aspect
@Component
@Order(1000)
@RequiredArgsConstructor
@Slf4j
public class AtomizationAop {

    private final PlatformTransactionManager transactionManager;

    @Pointcut("@annotation(com.example.demo.annotate.Atomization)")
    public void AtomizationAop() {

    }

    @Around("AtomizationAop()")
    public Object around(ProceedingJoinPoint joinPoint) {
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        Object obj;

        try {
            obj = joinPoint.proceed();
            transactionManager.commit(status);
        }
        catch (Throwable ex) {
            transactionManager.rollback(status);
            throw new BusinessException("事务回滚:" + ex);
        }

        return obj;
    }

}
